import asyncio
from playwright.async_api import async_playwright
import random
import os

class XiaohongshuAutoPublisher:
    def __init__(self):
        self.browser = None
        self.page = None
    
    async def init_browser(self):
        """初始化浏览器连接"""
        try:
            playwright = await async_playwright().start()
            self.browser = await playwright.chromium.connect_over_cdp(
                "http://localhost:9222"
            )
            self.context = self.browser.contexts[0]
            self.page = self.context.pages[0] if self.context.pages else await self.context.new_page()
            
            # 设置超时时间
            self.page.set_default_timeout(30000)
            return True
        except Exception as e:
            print(f"❌ 浏览器连接失败: {e}")
            return False
    
    async def goto_create_page(self):
        """导航到创作中心"""
        try:
            await self.page.goto('https://creator.xiaohongshu.com/publish/publish?source=official', wait_until='networkidle')
            
            # 等待发布界面加载完成
            await self.page.wait_for_selector('div[contenteditable="true"]', timeout=15000)
            print("✅ 成功进入创作中心")
            return True
        except Exception as e:
            print(f"❌ 进入创作中心失败: {e}")
            await self.page.screenshot(path='error_create_page.png')
            return False
    
    async def upload_images(self, image_paths):
        """上传图片"""
        try:
            # 等待文件上传输入框
            await self.page.wait_for_selector('input[type="file"]', timeout=10000)
            
            # 获取文件上传句柄
            file_input = await self.page.query_selector('input[type="file"]')
            
            if isinstance(image_paths, str):
                image_paths = [image_paths]
            
            await file_input.set_input_files(image_paths)
            print("✅ 图片上传成功")
            
            # 等待图片处理完成
            await self.page.wait_for_selector('img[src*="upload"]', timeout=30000)
            await asyncio.sleep(2)  # 额外等待确保完全加载
            return True
        except Exception as e:
            print(f"❌ 图片上传失败: {e}")
            await self.page.screenshot(path='error_upload.png')
            return False
    
    async def input_content(self, content, tags):
        """输入正文内容和标签"""
        try:
            # 定位正文编辑器
            editor = await self.page.wait_for_selector('div[contenteditable="true"]', timeout=10000)
            
            # 清空现有内容
            await editor.click(click_count=3)  # 三击全选
            await self.page.keyboard.press('Backspace')
            
            # 输入内容
            await editor.type(content)
            
            # 添加标签
            if tags:
                tag_text = ' ' + ' '.join([f'#{tag}' for tag in tags])
                await editor.type(tag_text)
            
            print("✅ 内容输入成功")
            
            # 添加随机延迟，模拟人类输入
            await asyncio.sleep(random.uniform(1, 3))
            return True
        except Exception as e:
            print(f"❌ 内容输入失败: {e}")
            await self.page.screenshot(path='error_content.png')
            return False
    
    async def publish(self):
        """执行发布操作"""
        try:
            # 定位发布按钮
            publish_button = await self.page.wait_for_selector('button:has-text("发布")', timeout=10000)
            await publish_button.click()
            print("✅ 已点击发布按钮")
            
            # 等待发布结果
            try:
                await self.page.wait_for_selector('text=发布成功', timeout=15000)
                print("🎉 发布成功！")
                return True
            except:
                # 检查是否有错误提示
                error_element = await self.page.query_selector('text=/发布失败|错误/')
                if error_element:
                    error_text = await error_element.inner_text()
                    print(f"❌ 发布失败: {error_text}")
                else:
                    print("⚠️  发布状态未知，请手动确认")
                return False
        except Exception as e:
            print(f"❌ 发布操作失败: {e}")
            await self.page.screenshot(path='error_publish.png')
            return False
    
    async def run(self, content, image_paths, tags=None):
        """执行完整发布流程"""
        if not await self.init_browser():
            return False
        
        try:
            steps = [
                (self.goto_create_page, "进入创作中心"),
                (lambda: self.upload_images(image_paths), "上传图片"),
                (lambda: self.input_content(content, tags), "输入内容"),
                (self.publish, "发布内容")
            ]
            
            for step_func, step_name in steps:
                print(f"▶️ 正在执行: {step_name}")
                if not await step_func():
                    print(f"❌ 流程中断于: {step_name}")
                    return False
                # 步骤间随机延迟
                await asyncio.sleep(random.uniform(1, 2))
            
            return True
        finally:
            if self.browser:
                await self.browser.close()

# 使用示例
async def main():
    publisher = XiaohongshuAutoPublisher()
    
    # 发布内容配置
    content = """
    🎉 祝中华人民共和国繁荣昌盛！🇨🇳
    
    用 Playwright MCP 自动化技术向祖国献礼！
    这是通过全自动脚本发布的小红书内容，展示了现代技术的魅力。
    
    科技强国，自动化助力美好生活！✨
    """
    
    # 使用准备好的国庆主题图片
    image_paths = [
        'sample/background.jpg'  # 国庆主题背景图
    ]
    
    tags = ['国庆节', '祖国万岁', '技术分享', '自动化', 'Playwright']
    
    success = await publisher.run(content, image_paths, tags)
    if success:
        print("🎉 自动化发布流程完成！")
    else:
        print("❌ 发布流程失败")

if __name__ == "__main__":
    asyncio.run(main())
